import React,{Component} from 'react';
import {View,Text,TextInput,Alert,TouchableOpacity,Image,ScrollView} from 'react-native';
import styles from './styles';
import cgStyles from '../cpgl/styles';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import {naviPush , naviBack} from '../../navigatorApp/actions';
import {connect} from 'react-redux';
import BigButton from '../../component/BigButton'
import themeconfig from '../../config/theme'
import ChooseModal from '../compents/ChooseModal';
import {  getRandOrderNo , getProgrameAnYou , addProgram} from "./actions";
const imageOptions = ['取消', '拍照上传'];
const CANCEL_INDEX = 0;
import config from '../../config/config';
import ChoosePhotoView from '../compents/ChoosePhotoView';
import ActionSheet from 'react-native-actionsheet';
const md5 = require('md5');
import moment from 'moment';
import { ArrayUtil } from '../../utils/common';
import { setConfigValue  , getConfig , getLocation , setBlueTooth ,printer, toast  ,  choosePhoto, printerProgram} from '../../utils/NativeUtil';
import {setPrinter , GetWeiZhangTCNum} from '../main/actions';


class Program extends Component {
    static navigationOptions = ({ navigation, screenProps }) => {
        const {params = {}} = navigation.state;
        let  header =  <CLNavigatorHeader navigation={navigation} title="简易程序" leftAction={params.backAction}/>
        return {header};
    };

    constructor(props){
        super(props);
        this.state={
            title:'简易程序',
            cfPerson:'',// 处罚人
            cfPersonId: '',// Id
            Address: '',//
            t4_city:'张家港市',
            behavior:'未选择',
            cfMoney:'',//处罚金额
            behaviorVisible:false,
            orderNo:'自动生成',
            behaviorTypes: [], //处罚行为
            zjzp: [], //证据照片
            pjzp: [] , //票据照片
            showRemark: false,
            remark:''
        }
        this.RowGuid = '';
        this.behaviorIndex = -1;
        this.zfrId = "";
        this.printed = false;
        this.fromType = props.navigation.state.params.fromType || ""; // message
        this.CaseNum = ""
    }
      
    componentDidMount(){
        this.props.navigation.setParams({ backAction : this._backAction});

        if (this.fromType == "message"){
            this.CaseNum = this.props.navigation.state.params.CaseNum;
            this.setState({showRemark : true})
        }


        let params = {
            UserGuid: this.props.userGuid,
            Password: md5(this.props.userGuid + config.md5Secret)
        }
        console.log(params);
        getProgrameAnYou(params).then(res => {
            console.log(res)
            this.setState({behaviorTypes:res})
        }).catch(msg => {
            console.log(msg)
        });

        this.getRandOrderNoAction();



        getLocation(res => {
            if (res == null || res == undefined) {
        
            } else {
                this.JinDu = res.lon;
                this.WeiDu = res.lat;
            }

            getConfig('wzdd' , res2 => {
                let lastAddress = res2.wzdd;
                if (lastAddress.length > 0){
                    this.setState({
                        Address: lastAddress
                    });
                }else {
                    if(res2.address!=undefined){
                    let address  = '张家港市' +  res2.address;
                    this.setState({
                        Address: address
                    });
                }
            }
            });
        });

 

        getConfig("c1_text",res => {
            this.zfrId = res.c1_text;
        });

    }


    getLocationAction = () => {
        getLocation(res => {
            if (res == null || res == undefined) {
                return;
            }  
            this.JinDu = res.lon;
            this.WeiDu = res.lat;
            let address  =  '张家港市' + res.address;

            this.setState({
                Address: address
            });
    });
    }


    _backAction = () => {
        Alert.alert('提示',
        "是否返回",
        [
            {text: '否', onPress: () => {}},
            {text: '是', onPress: () => { this.props.naviBack();}},
        ]);
    };

    getRandOrderNoAction = () => {
        if (this.state.orderNo == '自动生成'){
            getRandOrderNo(this.props.userGuid).then(res => {
                console.log(res)
                let data = res[0];
                this.setState({orderNo : data.CaseNo});
                this.RowGuid = data.RowGuid;
            }).catch(msg => {
                console.error(msg)
            });
        }
    }

    chooseItemClick = (item, tag) => {
        this.photoLstTag = tag;
        this.phtotoItem = item;
        this.ImageActionSheet.show();
    };

    handleImagePress = (i) => {
        let type = "choose";
        let size_w = 0;
        let size_h = 0;
        if (i == 1) {
            type = "takephoto"
        } else if (i == 2) {
            type = "choose"
        } else {
            return;
        }

         
        let params = {
            type : type,
            fileType: this.photoLstTag,
            recordGuid: this.RowGuid,
        }

        if (this.photoLstTag == 'jycxPj') {
            params.photos = this.state.pjzp
        } else {
            params.photos = this.state.zjzp
        }

        console.log(params);
        choosePhoto(params , data => {
             let imgs = data.imgs;
             console.log(data);
           
                if (this.photoLstTag == 'jycxPj'){
                    let lst = [];
                    if (imgs != ''){
                        let imgItem = imgs.split(';');
                        imgItem.map(item => {
                            if (item.length != ''){
                                lst.push({url: item , id: lst.length  , title: ''});
                            }
                        })
                    }  
                    this.setState({
                        pjzp: lst
                    });
                } else if (this.photoLstTag == 'ocr_person'){
                    if (imgs != ''){
                        let infos = imgs.split(';');
                        this.setState({cfPerson:infos[1] , cfPersonId:infos[0]});
                    } else {
                        toast('请选择照片')
                    }
                } else {
                    let lst = [];
                    if (imgs != ''){
                        let imgItem = imgs.split(';');
                        imgItem.map(item => {
                            if (item.length != ''){
                                lst.push({url: item , id: lst.length  , title: ''});
                            }
                        })
                    }
                    this.setState({
                        zjzp: lst
                    });
                }
             
        });
    };


    printerAction = () => {

         // 判断蓝牙连接状态
        if (this.props.blueToothState == '未连接') {
            toast ('请先连接打印机')
            return;
        }

        if (this.checkValue()){
    
        let curBehavior = this.state.behaviorTypes[this.state.behaviorIndex];
        let params = {
            cfNo : this.state.orderNo,
            dsrPerson : this.state.cfPerson , 
            dsrId: this.state.cfPersonId,
            printDate: moment().format("YYYY年MM月DD日"),
            cfAddress: this.state.Address,
            cfXw: curBehavior.AnYou,
            wfYj: curBehavior.WFYJ,
            cfYj: curBehavior.CFYJ,
            cfJe: this.state.cfMoney,
            zfrName: this.props.userName , 
            zfrId: this.zfrId
        }
        console.log(params);
        printerProgram(params , res => {
            this.printed = true
        });
    }
    }

    checkPesonId = (id) => {
        let reg = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
        return reg.test(id);
    }

    checkPrice = (prie) => {
        let reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
        return reg.test(prie)
    }

    checkValue = () => {
        if (this.state.cfPerson.length  == 0 ){
             toast('请输入当事人姓名')
             return false;
        }
    

       if (!this.checkPesonId(this.state.cfPersonId)) {
        toast('请输入正确的当事人身份证')
        return
       }
       


       if (this.state.Address.length == 0){
        toast('请输入地点')
        return false;
       }

       if (!this.checkPrice(this.state.cfMoney)) {
        toast('请输入正确处罚金额')
        return false;
       }

       if (this.state.behaviorIndex  == -1 ){
            toast('请选择处罚行为')
            return false;
        } 
        return true;
    }

      /**
     * 保存 信息
     */
    saveInfo = () => {
        setConfigValue('wzdd' , this.state.Address || '');
    }

    submit = () => {
        if (this.checkValue()){
            if (this.state.pjzp.length == 0 ){
                toast('请至少上传1张票据照片')
                return;
            }
            if (this.printed){
                let params = {
                    RowGuid: this.RowGuid,
                    CaseNo: this.state.orderNo,
                    ChuFaRen: this.state.cfPerson,
                    CertID:	this.state.cfPersonId,
                    ChuFaDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    Address: this.state.Address,
                    ChuFaXW: this.state.behavior,
                    JinE: this.state.cfMoney,
                    DisplayName: this.props.userName,
                    UserGuid: this.props.userGuid,
                    Password: md5(this.props.userGuid + config.md5Secret),
                    CaseNum: this.CaseNum,
                    remark: this.state.remark
                }
               
                console.log(params);
                
                addProgram(params).then(res => {
                    toast('提交成功')
                    this.saveInfo();
                    this.props.naviBack();
                }).catch(msg => {})
            } else {
                toast('请先打印')
                return;
            }
        }
    }

    setBlueToothAction = () => {
        setBlueTooth(res => {
            console.log(res);
            if (res.name && res.name.length > 0 ){
                this.props.setPrinter(res.name)
            }
        });
    }

    delPhotos = ( tag ,  item , index) => {
        console.log(item)
        console.log(index)
        if (tag == 'jycxZp'){
            let pjzpPhotos = this.state.pjzp;
            ArrayUtil.delete(pjzpPhotos , item);
            this.setState({pjzp:pjzpPhotos})
        } else {
            let zjzpPhotos = this.state.zjzp;
            ArrayUtil.delete(zjzpPhotos , item);
            this.setState({zjzp:zjzpPhotos})
        }
    }

    takePersonAction = () => {
        this.photoLstTag = "ocr_person";
        this.ImageActionSheet.show();
    }
 
    setPrice = (item , index) => {
        let price  = this.state.behaviorTypes[index].MinJE
        this.setState({behaviorIndex:index , behavior:item,behaviorVisible:false , cfMoney:price})
    }

    render(){

        let behaviorType = []
        this.state.behaviorTypes.map(item => {
            behaviorType.push(item.AnYou)
        });
        
        return (
            <ScrollView style={styles.totalbox}>
                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>处罚编码</Text>
                    <TouchableOpacity style={cgStyles.centerView} onPress={this.getRandOrderNoAction}>
                        <Text style={[cgStyles.rightValue]}>{this.state.orderNo}</Text>
                    </TouchableOpacity>
                </View>

                {
                    this.state.showRemark ? (<View style={cgStyles.itemView}>
                        <Text style={cgStyles.lableText}>派单单号</Text>
                        <TouchableOpacity style={cgStyles.centerView}>
                            <Text style={[cgStyles.rightValue]}>{this.CaseNum}</Text>
                        </TouchableOpacity>
                    </View>) : null
                }

                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>当事人</Text>
                    <TextInput 
                    value={this.state.cfPerson} 
                    underlineColorAndroid="transparent"
                    onChangeText={(txt)=>this.setState({cfPerson:txt})}
                    style={styles.t1} placeholder='当事人姓名'/>
                     <TouchableOpacity style={cgStyles.rightCpBtn} onPress={this.takePersonAction}>
                     <Text style={{color:'white'}}>拍照识别</Text>  
                    </TouchableOpacity>
                </View>
                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>身份证</Text>
                    <TextInput value={this.state.cfPersonId} 
                      onChangeText={(txt)=>this.setState({cfPersonId:txt})}
                      underlineColorAndroid="transparent"
                        style={styles.t1} placeholder='当事人身份证号'/>
                </View>
                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>处罚地点</Text>
                     
                    <TextInput 
                        value={this.state.Address} 
                        numberOfLines={3}
                        underlineColorAndroid="transparent"
                        onChangeText={(txt)=>this.setState({Address:txt})}
                        style={styles.t4} placeholder='详细地址'/>
                     
                     <TouchableOpacity style={cgStyles.rightCpBtn} onPress={()=>this.getLocationAction()}>
                <Text style={{color:'white'}}>获取位置</Text>
            </TouchableOpacity>
                </View>




                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>处罚行为</Text>
                   <TouchableOpacity 
            onPress={()=>this.setState({behaviorVisible:true})}
            style={[cgStyles.chooseStyle,{flex:1}]}>
                <Text style={[cgStyles.rightValue , {flex:1}]}>{this.state.behavior}</Text>
                <Image source={require('../../image/icon_down_grey.png')} style={{width:16, height:16}}></Image>
            </TouchableOpacity>
                </View>
                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>处罚金额</Text>
                    <View style={styles._t6}>
                        <Text style={styles.t6_text}>¥</Text>
                        <TextInput 
                            underlineColorAndroid="transparent"
                            value={this.state.cfMoney} 
                            style={styles.t6} 
                            onChangeText={txt => this.setState({cfMoney:txt})}/>
                    </View>
                </View>

{
    this.state.showRemark ? ( <View style={cgStyles.itemView}>
        <Text style={cgStyles.lableText}>处理意见</Text>
        <View style={styles._t6}>
            <TextInput 
                value={this.state.remark} 
                style={styles.t6} 
                underlineColorAndroid="transparent"
                onChangeText={txt => this.setState({remark:txt})}/>
        </View>
    </View>) : null
}


                <View style={cgStyles.itemView}>
                    <Text style={[cgStyles.lableText,{width:100}]}>票据照片<Text style={cgStyles.warnText}>(必传)</Text></Text>
                </View>
                <ChoosePhotoView 
                    onItemClick={(item) => this.chooseItemClick(item, 'jycxPj')}
                    images={this.state.pjzp} num={3}
                    delAction={(item , index)=>this.delPhotos( 'jycxPj' , item, index)}
                    itemheight={80}
                />
                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>证据照片</Text>
                </View>
                <ChoosePhotoView 
                    onItemClick={(item) => this.chooseItemClick(item, 'jycxZp')}
                    images={this.state.zjzp} num={3}
                    delAction={(item , index)=>this.delPhotos( 'jycxZp' , item, index)}
                    itemheight={80}
                />

                {/* <View style={Styles.itemView}>
                    <Text style={Styles.lableText}>蓝牙</Text>
                    <Text style={styles.t9}>{this.props.blueToothState}</Text>
                    <TouchableOpacity  onPress={this.setBlueToothAction} style={styles.bt}><Text style={styles.bt_label}>设置</Text></TouchableOpacity>
                </View> */}

                <View style={cgStyles.itemView}>
                    <Text style={cgStyles.lableText}>蓝牙</Text>
                    <View style={cgStyles.centerView}>
                        <Text style={cgStyles.rightValue}>{this.props.blueToothState}</Text>
                    </View>
            <TouchableOpacity style={cgStyles.rightBtn} onPress={this.setBlueToothAction}>
               <Text style={cgStyles.settingTxt}>设置</Text>
            </TouchableOpacity>
        </View>

                <View style={styles.blank2}/>

                <BigButton style={{marginTop:10 }}  onPress={this.printerAction} label='打印' backgroundColor={themeconfig.blue3Color}/>

                <BigButton style={{marginTop:10 }} onPress={()=> this.submit()} label='提交' backgroundColor={themeconfig.blue1Color}/>
               
                <View style={styles.blank3}/>
                <ChooseModal 
                    modalVisible={this.state.behaviorVisible}
                    onSure={(item,  index)=> this.setPrice(item,index)}
                    lstStr={behaviorType}
                    title="处罚行为"
                    hideAction={()=>this.setState({behaviorVisible:false})}></ChooseModal>

         <ActionSheet
                ref={o => this.ImageActionSheet = o}
                title="选择图片"
                options={imageOptions}
                cancelButtonIndex={CANCEL_INDEX}
                onPress={this.handleImagePress}/>
            </ScrollView>
        )
    }
}

const mapStateToProps = state => ({
    userName : state.main.userName,
    blueToothState: state.main.printerName,
    userGuid: state.main.UserGuid
});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName, params) => {
        dispatch(naviPush(routeName, params));
    },
    naviBack: (routeName) =>{
        dispatch(naviBack(routeName))
    },
    setPrinter: (name) => {
        dispatch(setPrinter(name));
    },
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Program);


